package org.summer.web.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedissonConfigImpl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.redisson.api.RedissonClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Configuration
@EnableConfigurationProperties(WxProperties.class)
public class WxConfig {


    @Bean
    public WxMaService wxMaService(WxProperties properties) {
        WxMaService wxMaService = new WxMaServiceImpl();
        List<WxProperties.Config> configs = properties.getConfigs();
        if(CollUtil.isNotEmpty(configs)){
            RedissonClient redissonClient =SpringUtil.getBean(RedissonClient.class);
            wxMaService.setMultiConfigs(
                    configs.stream().map(item ->{
                        WxMaDefaultConfigImpl config = new WxMaRedissonConfigImpl(redissonClient);
                     config.setAppid(item.getAppid());
                     config.setSecret(item.getSecret());
                     config.setMsgDataFormat(item.getMsgDataFormat());
                     return config;
                    }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid,item -> item, (o,n) -> o)));
        }
        return wxMaService;
    }


}
